package Form::Field::YearRange;
use strict;
use warnings;
use base qw(My::Form::Field::Compound);
use Rose::HTML::Form::Field::PopUpMenu;

sub build_field {
    my ($self) = shift;
    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time);
    my %params;
    $params{size}  = 1;
    $params{name}  = 'from_year';
    $params{class} = $self->class if ( $self->class );
    my $from_year = Rose::HTML::Form::Field::PopUpMenu->new(%params);
    $params{name} = 'to_year';
    my $to_year = Rose::HTML::Form::Field::PopUpMenu->new(%params);

    # initialise drop boxes
    $from_year->add_options( undef => undef );
    $to_year->add_options( undef => undef );
    for ( reverse( ( $year + 1900 - 100 ) .. ( $year + 1900 ) ) ) {
        $from_year->add_options( $_ => $_ );
        $to_year->add_options( $_ => $_ );
    }
    $self->add_fields( from_year => $from_year, to_year => $to_year, );
} ## end sub build_field

sub coalesce_value {
    my ($self) = shift;
    if ( $self->field('from_year')->internal_value && $self->field('to_year')->internal_value ) {
        return
            join( '-',
                  map { defined($_) ? $_ : '' }
                      map { $self->field($_)->internal_value } qw(from_year to_year) );
    }
}

sub decompose_value {
    my ( $self, $value ) = @_;
    return undef unless ( defined($value) );
    if ( $value =~ /^(\d{4})-(\d{4}|\d{0})?$/ ) {
        return { from_year => $1, to_year => ( $2 ? $2 : undef ) };
    }
} ## end sub decompose_value

sub html {
    my ($self) = shift;
    my $html = $self->field('from_year')->html . '&ndash;' . $self->field('to_year')->html;
    return $html . $self->html_error();
} ## end sub html

sub validate {
    my ($self) = shift;

    # the superclass validator will handle all the builtins, like required etc.
    if ( !$self->SUPER::validate() ) { return; }
    if ( $self->field('from_year')->internal_value && $self->field('to_year')->internal_value ) {
        if ( $self->field('from_year')->internal_value <= $self->field('to_year')->internal_value ) {
            return 1;
        } elsif ($self->field('to_year')->internal_value !~ /^undef$/) {
            $self->error("Year range ended before it began.");
        }
        return;
    } elsif ( $self->field('from_year')->internal_value && !$self->field('to_year')->internal_value ) {

        # unbounded range, still ongoing
        return 1;
    } elsif ( !$self->field('from_year')->internal_value && $self->field('to_year')->internal_value ) {
        $self->error("Starting year not specified.");

        # doesn't make sense, no starting date?
        return;
    }
} ## end sub validate
1;
